-- SPDX-License-Identifier: GPL-3.0-or-later

local extension = Package("ling7")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"
local LUtil = require "packages/lingling/utility/ling_util"


local zhaopu = General(extension, "lingling__zhaopu", "song", 3)
local zhifa = fk.CreateActiveSkill{
  name = "lingling__zhifa",
  anim_type = "drawcard",
  card_num = 1,
  min_target_num = 0,
  max_target_num = 1,
  prompt = "#lingling__zhifa",
  times = function(self)
    return player.phase == Player.Play and 2 - player:usedSkillTimes(self.name, Player.HistoryPhase) or -1
  end,
  can_use = function (self, player, card, extra_data)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 2
  end,
  card_filter = function(self, player, to_select, selected, targets)
    return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeTrick
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= player
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    if #effect.tos > 0 then
      local target = room:getPlayerById(effect.tos[1])
      room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, true, player.id)
    else
      room:recastCard(effect.cards, player, self.name)
    end
    if not player.dead then
      player:drawCards(2, self.name)
    end
  end,
}
local shenbei = fk.CreateTriggerSkill{
  name = "lingling__shenbei",
  anim_type = "masochism",
  events = {fk.Damaged, fk.Deathed},
  can_trigger = function(self, event, target, player, data)
    if target == player then
      if event == fk.Damaged then
        return player:hasSkill(self)
      elseif event == fk.Deathed then
        return player:hasSkill(self, false, true) and
          table.find(player.room.alive_players, function (p)
            return not p:hasSkill(self, true)
          end)
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    if event == fk.Damaged then
      for i = 1, data.damage do
        if not player:hasSkill(self) then return end
        self:doCost(event, target, player, data)
      end
    elseif event == fk.Deathed then
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.Damaged then
      self.cost_data = nil
      return true
    elseif event == fk.Deathed then
      local room = player.room
      local targets = table.filter(room.alive_players, function (p)
        return not p:hasSkill(self, true)
      end)
      local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1,
        "#lingling__shenbei-choose", self.name, true)
      if #to > 0 then
        self.cost_data = {tos = to}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.Damaged then
      local cards = room:getCardsFromPileByRule(".|.|.|.|.|trick", 1, "allPiles")
      if #cards > 0 then
        room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, false, player.id)
      end
    elseif event == fk.Deathed then
      local to = room:getPlayerById(self.cost_data.tos[1])
      room:handleAddLoseSkills(to, self.name, nil, true, false)
    end
  end,
}
zhaopu:addSkill(zhifa)
zhaopu:addSkill(shenbei)
Fk:loadTranslationTable{
  ["lingling__zhaopu"] = "赵普",
  ["#lingling__zhaopu"] = "兴王开运",
  ["illustrator:lingling__zhaopu"] = "珊瑚虫",
  ["designer:lingling__zhaopu"] = "伶",

  ["lingling__zhifa"] = "制法",
  [":lingling__zhifa"] = "出牌阶段限两次，你可以将一张锦囊牌交给一名其他角色或重铸，然后摸两张牌。",
  ["lingling__shenbei"] = "神碑",
  [":lingling__shenbei"] = "当你受到1点伤害后，你随机获得一张锦囊牌。当你死亡后，你可以令一名其他角色获得此技能。"..
  "<br><br> <font color = '#a40000'>抑抑人杰，佐命之元。",
  ["#lingling__zhifa"] = "制法：选择一张锦囊牌，交给一名其他角色，或不选目标重铸之，然后你摸两张牌",
  ["#lingling__shenbei-choose"] = "神碑：你可以令一名角色获得“神碑”",
}

local fanzhongyan = General(extension, "lingling__fanzhongyan", "song", 3)
local mingsi = fk.CreateTriggerSkill{
  name = "lingling__mingsi",
  anim_type = "control",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target:inMyAttackRange(player)
  end,
  on_cost = function (self, event, target, player, data)
    local use = U.askForPlayCard(player.room, player, nil, nil, self.name, "#lingling__mingsi-use", {bypass_times = true}, true)
    if use then
      self.cost_data = use
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local use = self.cost_data
    use.extraUse = true
    local n = use.card.type == Card.TypeTrick and 2 or 1
    player:drawCards(n, self.name)
    room:useCard(use)
    if target.dead or player.dead then return end
    local yes = #room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
      local u = e.data[1]
      return u.from == target.id and u.card.trueName == use.card.trueName
    end, Player.HistoryTurn) == 0
    if yes then
      use = room:askForUseCard(target, self.name, "slash", "#lingling__mingsi-slash:"..player.id, true,
        {
          bypass_distances = true,
          bypass_times = true,
          must_targets = {player.id},
        })
      if use then
        use.extraUse = true
        room:useCard(use)
      end
    end
  end,
}
local youle = fk.CreateTriggerSkill{
  name = "lingling__youle",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseChanging, fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.EventPhaseChanging then
        return data.to == Player.Draw or data.to == Player.Discard
      elseif event == fk.DrawNCards then
        return 2 * #table.filter(player.room.alive_players, function (p)
          return p:isWounded()
        end) < #player.room.alive_players
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.EventPhaseChanging then
      if data.to == Player.Draw then
        data.to = Player.Discard
      elseif data.to == Player.Discard then
        data.to = Player.Draw
      end
    elseif event == fk.DrawNCards then
      data.n = data.n + 1
    end
  end,
}
local youle_maxcards = fk.CreateMaxCardsSkill{
  name = "#youle_maxcards",
  correct_func = function(self, player)
    if player:hasSkill(youle) then
      return 1
    end
  end,
}
youle:addRelatedSkill(youle_maxcards)
fanzhongyan:addSkill(mingsi)
fanzhongyan:addSkill(youle)
Fk:loadTranslationTable{
  ["lingling__fanzhongyan"] = "范仲淹",
  ["#lingling__fanzhongyan"] = "一世之师",
  ["illustrator:lingling__fanzhongyan"] = "珊瑚虫",
  ["designer:lingling__fanzhongyan"] = "伶",

  ["lingling__mingsi"] = "鸣死",
  [":lingling__mingsi"] = "攻击范围内有你的其他角色回合结束时，你可以使用一张牌并摸一张牌（使用锦囊牌则摸两张），若与其本回合使用的牌名称皆不同，"..
  "则其可以对你使用一张【杀】。",
  ["lingling__youle"] = "忧乐",
  [":lingling__youle"] = "你的手牌上限+1。你交换摸牌阶段和弃牌阶段的顺序。若场上受伤角色数少于一半，则摸牌阶段你多摸一张牌。"..
  "<br><br> <font color = '#a40000'>为社稷之固者，莫知范仲淹。",
  ["#lingling__mingsi-use"] = "鸣死：你可以使用一张牌并摸一张牌，使用锦囊牌则摸两张",
  ["#lingling__mingsi-slash"] = "鸣死：是否对 %src 使用一张【杀】？",
}

local wanganshi = General(extension, "lingling__wanganshi", "song", 3)
local gexin = fk.CreateTriggerSkill{
  name = "lingling__gexin",
  anim_type = "control",
  events = {fk.AskForRetrial},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and not player:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local card = {}
    local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
    if turn_event == nil or turn_event.data[1] ~= player then
      card = room:askForDiscard(player, 1, 1, true, self.name, true, nil,
        "#lingling__gexin-discard::"..target.id..":"..data.reason, true)
    else
      card = room:askForCard(player, 1, 1, true, self.name, true, nil,
        "#lingling__gexin-recast::"..target.id..":"..data.reason)
    end
    if #card > 0 then
      self.cost_data = {cards = card}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local yes = false
    local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
    if turn_event == nil or turn_event.data[1] ~= player then
      yes = true
    end
    if yes then
      room:throwCard(self.cost_data.cards, self.name, player, player)
    else
      room:recastCard(self.cost_data.cards, player, self.name)
    end
    if player.dead then return end
    local cards = room:getNCards(3)
    room:moveCardTo(cards, Card.Processing, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
    if player.dead then
      room:cleanProcessingArea(cards)
      return
    end
    local card = U.askforChooseCardsAndChoice(player, cards, {"OK"}, self.name, "#lingling__gexin-retrial",{"Cancel"})
    if #card then
      table.removeOne(cards, card[1])
      room:retrial(Fk:getCardById(card[1]), player, data, self.name, false)
    end
    if player.dead then
      room:cleanProcessingArea(cards)
      return
    end
    if #cards > 0 then
      card = U.askforChooseCardsAndChoice(player, cards, {"OK"}, self.name, "#lingling__gexin-prey")
      room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
    room:cleanProcessingArea(cards)
    if not player.dead and yes then
      room:invalidateSkill(player, self.name, "-turn")
    end
  end,
}
local gongsi = fk.CreateTriggerSkill{
  name = "lingling__gongsi",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Judge and
      #player:getCardIds("j") == 0
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    for i = 1, 2, 1 do
      if player.dead then return end
      local judge = {
        who = target,
        reason = self.name,
        pattern = ".|.|spade,heart",
        skipDrop = true,
      }
      room:judge(judge)
      if judge.card.suit == Card.Heart then
        if not player.dead and room:getCardArea(judge.card) == Card.Processing then
          if room:askForSkillInvoke(player, self.name, nil, "#lingling__gongsi-prey:::"..judge.card:toLogString()) then
            room:moveCardTo(judge.card, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
          end
        end
      elseif judge.card.suit == Card.Spade then
        if not player.dead and room:getCardArea(judge.card) == Card.Processing and #room:getOtherPlayers(player) > 0 then
          local to = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1,
            "#lingling__gongsi-choose:::"..judge.card:toLogString(), self.name, true)
          if #to > 0 then
            room:moveCardTo(judge.card, Card.PlayerHand, to[1], fk.ReasonJustMove, self.name, nil, true, player.id)
          end
        end
      end
      if room:getCardArea(judge.card) == Card.Processing then
        room:moveCardTo(judge.card, Card.DiscardPile, nil, fk.ReasonJudge)
      end
    end
  end,
}
Fk:loadTranslationTable{
  ["lingling__wanganshi"] = "王安石",
  ["#lingling__wanganshi"] = "镇国之石",
  ["illustrator:lingling__wanganshi"] = "伊达未来",
  ["designer:lingling__wanganshi"] = "伶",

  ["lingling__gexin"] = "革新",
  [":lingling__gexin"] = "当一名角色的判定牌生效前，你可以弃置一张牌（若为你回合内则改为重铸），亮出牌堆顶三张牌并可用其中一张牌代替之，"..
  "然后你从剩余牌中获得一张。若为你的回合外，此技能本回合失效。",
  ["lingling__gongsi"] = "公私",
  [":lingling__gongsi"] = "判定阶段，若你判定区没有牌，你可以判定两次，若为<font color='red'>♥</font>你可以获得之，若为♠你可以令一名"..
  "其他角色获得之。"..
  "<br><br> <font color = '#a40000'>上与介甫如一人，此乃天也。",
  ["#lingling__gexin-discard"] = "朝柄：%dest 进行“%arg”判定，是否弃置一张牌，从牌堆顶三张牌中选一张牌代替之？",
  ["#lingling__gexin-recast"] = "朝柄：%dest 进行“%arg”判定，是否重铸一张牌，从牌堆顶三张牌中选一张牌代替之？",
  ["#lingling__gexin-retrial"] = "革新：选择用来修改判定的牌",
  ["#lingling__gexin-prey"] = "革新：获得其中一张牌",
  ["#lingling__gongsi-prey"] = "公私：是否获得%arg？",
  ["#lingling__gongsi-choose"] = "公私：是否令一名其他角色获得%arg？",
}

local zongze = General(extension, "lingling__zongze", "song", 3)
local duhe = fk.CreateActiveSkill{
  name = "lingling__duhe",
  anim_type = "offensive",
  card_num = 1,
  target_num = 1,
  prompt = "#lingling__duhe",
  target_tip = function(self, to_select, selected, selected_cards, _, selectable)
    if not selectable then return end
    if player:getLastAlive().id == to_select or player:getNextAlive().id == to_select then
      return "lingling__duhe_tip_1"
    else
      return "lingling__duhe_tip_2"
    end
  end,
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function (self, player, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "jink"
  end,
  target_filter = function(self, player, to_select, selected)
    if #selected == 0 then
      if player:getLastAlive().id == to_select or player:getNextAlive().id == to_select then
        return not Fk:currentRoom():getPlayerById(to_select):isNude() --and player:getMark("lingling__duhe2-phase") == 0
      else
        return true --player:getMark("lingling__duhe1-phase") == 0
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:recastCard(effect.cards, player, self.name)
    if target.dead then return end
    if player:getLastAlive() == target or player:getNextAlive() == target then
      --room:setPlayerMark(player, "lingling__duhe2-phase", 1)
      if not player.dead and not target:isNude() and target ~= player then
        local card = room:askForCardChosen(player, target, "he", self.name, "#lingling__duhe-prey::"..target.id)
        room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      end
    else
      --room:setPlayerMark(player, "lingling__duhe1-phase", 1)
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    end
  end,
}
local duhe_trigger = fk.CreateTriggerSkill{
  name = "#lingling__duhe_trigger",
  anim_type = "masochism",
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(duhe)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local cards = room:getCardsFromPileByRule("jink", 1, "allPiles")
    if #cards > 0 then
      room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, "lingling__duhe", nil, true, player.id)
    end
  end,
}
local shangyou = fk.CreateTriggerSkill{
  name = "lingling__shangyou",
  anim_type = "control",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and not player:isKongcheng() and #player:getTableMark(self.name) < 3
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local success, dat = room:askForUseActiveSkill(player, "lingling__shangyou_active", "#lingling__shangyou-invoke", true)
    if success and dat then
      self.cost_data = {cards = dat.cards, choice = dat.interaction}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addTableMark(player, self.name, Util.PhaseStrMapper(self.cost_data.choice))
    room:recastCard(self.cost_data.cards, player, self.name)
    if player.dead then return end
    room:loseHp(player, 1, self.name)
    if player.dead then return end
    local to = player:getLastAlive(true)
    if to == player then return end
    room:swapSeat(player, to)
    if room:askForSkillInvoke(player, self.name, nil, "#lingling__shangyou-ask::"..to.id) then
      to:turnOver()
    end
    if self:triggerable(event, target, player, data) then
      self:doCost(event, target, player, data)
    end
  end,

  refresh_events = {fk.EventPhaseChanging},
  can_refresh = function(self, event, target, player, data)
    return target == player and table.contains(player:getTableMark(self.name), data.to)
  end,
  on_refresh = function(self, event, target, player, data)
    data.to = Player.Play
  end,
}
local shangyou_active = fk.CreateActiveSkill{
  name = "lingling__shangyou_active",
  card_num = 1,
  target_num = 0,
  interaction = function()
    local all_choices = {"phase_judge", "phase_draw", "phase_discard"}
    local choices = table.filter(all_choices, function (s)
      return not table.contains(player:getTableMark("lingling__shangyou"), Util.PhaseStrMapper(s))
    end)
    return UI.ComboBox {choices = choices, all_choices = all_choices}
  end,
  card_filter = function (self, player, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "slash"
  end,
}
duhe:addRelatedSkill(duhe_trigger)
Fk:addSkill(shangyou_active)
zongze:addSkill(duhe)
zongze:addSkill(shangyou)
Fk:loadTranslationTable{
  ["lingling__zongze"] = "宗泽",
  ["#lingling__zongze"] = "日月争光",
  ["illustrator:lingling__zongze"] = "伊达未来",
  ["designer:lingling__zongze"] = "伶",

  ["lingling__duhe"] = "渡河",
  [":lingling__duhe"] = "出牌阶段限一次，你可以重铸一张【闪】，然后对一名与你不相邻的角色造成1点伤害，或获得一名与你相邻的角色一张牌。"..
  "当你受到伤害后，你获得一张【闪】。",
  ["lingling__shangyou"] = "上游",
  [":lingling__shangyou"] = "回合结束时，你可以执行任意次：重铸一张【杀】并失去1点体力，将一个出牌阶段外的阶段（判定阶段、摸牌阶段、弃牌阶段）"..
  "永久变为出牌阶段，然后与上家交换位置，且你可以令其翻面。"..
  "<br><br> <font color = '#a40000'>谁人共挽天河水，尽洗中原犬虏腥。",
  ["#lingling__duhe"] = "渡河：重铸一张【闪】，对一名不相邻角色造成1点伤害，或获得一名相邻角色一张牌",
  ["lingling__duhe_tip_1"] = "获得牌",
  ["lingling__duhe_tip_2"] = "造成伤害",
  ["#lingling__duhe-prey"] = "渡河：获得 %dest 一张牌",
  ["#lingling__duhe_trigger"] = "渡河",
  ["lingling__shangyou_active"] = "上游",
  ["#lingling__shangyou-invoke"] = "上游：是否重铸一张【杀】并失去1点体力，将一个阶段改为出牌阶段并与上家交换位置？",
  ["#lingling__shangyou-ask"] = "上游：是否令 %dest 翻面？",
}

local hanshizhong = General(extension, "lingling__hanshizhong", "song", 4)
local jinglv = fk.CreateTriggerSkill{
  name = "lingling__jinglv",
  anim_type = "offensive",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick and
      data.tos and not data.card.multiple_targets and
      not table.contains(player:getTableMark("lingling__jinglv_names-turn"), data.card.name) then
      local tos = TargetGroup:getRealTargets(data.tos)
      return #tos == 1 and tos[1] ~= player.id and not player.room:getPlayerById(tos[1]).dead
    end
  end,
  on_cost = function(self, event, target, player, data)
    local tos = TargetGroup:getRealTargets(data.tos)
    if player.room:askForSkillInvoke(player, self.name, nil, "#lingling__jinglv-invoke::"..tos[1]..":"..data.card.name) then
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addTableMark(player, "lingling__jinglv_names-turn", data.card.name)
    local to = room:getPlayerById(self.cost_data.tos[1])
    room:damage{
      from = player,
      to = to,
      damage = 1,
      skillName = self.name,
    }
    if not to.dead then
      local mark = to:getTableMark(self.name)
      local info = mark[string.format("%.0f", player.id)] or {}
      table.insertIfNeed(info, data.card.name)
      mark[string.format("%.0f", player.id)] = info
      room:setPlayerMark(to, self.name, mark)
    end
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark(self.name) ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "lingling__jinglv-turn", player:getMark(self.name))
    room:setPlayerMark(player, self.name, 0)
    room:handleAddLoseSkills(player, "lingling__jinglv&", nil, false, true)
    room.logic:getCurrentEvent():findParent(GameEvent.Turn, true):addCleaner(function()
      room:handleAddLoseSkills(player, "-lingling__jinglv&", nil, false, true)
    end)
  end,
}
local jinglv_viewas = fk.CreateViewAsSkill{
  name = "lingling__jinglv&",
  anim_type = "negative",
  prompt = "#lingling__jinglv&",
  interaction = function(self)
    local all_names = {}
    for _, names in pairs(player:getMark("lingling__jinglv-turn")) do
      table.insertTable(all_names, names)
    end
    local names = player:getViewAsCardNames(player, self.name, all_names)
    if #names > 0 then
      return UI.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function (self, player, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, player, cards)
    if #cards == 0 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcard(cards[1])
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    local mark = player:getMark("lingling__jinglv-turn")
    local id = string.format("%.0f", TargetGroup:getRealTargets(use.tos)[1])
    for pId, names in pairs(mark) do
      if pId == id then
        for i = #names, 1, -1 do
          if names[i] == use.card.name then
            table.remove(mark[pId], i)
            break
          end
        end
      end
      if #mark[pId] == 0 then
        mark[pId] = nil
      end
    end
    if next(mark) then
      room:setPlayerMark(player, "lingling__jinglv-turn", mark)
    else
      room:setPlayerMark(player, "lingling__jinglv-turn", 0)
    end
  end,
  enabled_at_play = function(self, player)
    if player:getMark("lingling__jinglv-turn") == 0 then return end
    local mark = player:getMark("lingling__jinglv-turn")
    for _, p in ipairs(Fk:currentRoom().alive_players) do
      if mark[string.format("%.0f", p.id)] then
        return true
      end
    end
  end,
}
local jinglv_prohibit = fk.CreateProhibitSkill{  --FIXME: 目标多指！
  name = "#lingling__jinglv_prohibit",
  is_prohibited = function(self, from, to, card)
    if from:getMark("lingling__jinglv-turn") ~= 0 and card and table.contains(card.skillNames, "lingling__jinglv&") then
      for pId, names in pairs(from:getMark("lingling__jinglv-turn")) do
        if not (string.format("%.0f", to.id) == pId and table.contains(names, card.name)) then
          return true
        end
      end
    end
  end,
}
jinglv_viewas:addRelatedSkill(jinglv_prohibit)
Fk:addSkill(jinglv_viewas)
local yitun = fk.CreateTriggerSkill{
  name = "lingling__yitun",
  anim_type = "support",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick and data.from ~= player.id and
      not player:isKongcheng() and #player.room:getOtherPlayers(player) > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local success, dat = room:askForUseActiveSkill(player, "lingling__yitun_active", "#lingling__yitun-invoke", true)
    if success and dat then
      self.cost_data = {tos = dat.targets, cards = dat.cards, choice = dat.interaction}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if self.cost_data.choice == "lingling__yitun1" then
      local to = room:getPlayerById(self.cost_data.tos[1])
      room:setPlayerMark(to, "@@lingling__yitun", 1)
      room:moveCardTo(self.cost_data.cards, Card.PlayerHand, to, fk.ReasonGive, self.name, nil, false, player.id)
    else
      local judge = {
        who = player,
        reason = self.name,
        pattern = ".|.|heart,diamond",
      }
      room:judge(judge)
      if judge.card.color == Card.Red then
        if data.card.sub_type == Card.SubtypeDelayedTrick then
          AimGroup:cancelTarget(data, player.id)
        else
          table.insertIfNeed(data.nullifiedTargets, player.id)
        end
      end
    end
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return target == player and target:getMark("@@lingling__yitun") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@lingling__yitun", 0)
    room:setPlayerMark(player, "@@lingling__yitun-turn", 1)
    player:skip(Player.Judge)
    player:skip(Player.Discard)
  end,
}
local yitun_active = fk.CreateActiveSkill{
  name = "lingling__yitun_active",
  min_card_num = 0,
  max_card_num = 2,
  min_target_num = 0,
  max_target_num = 2,
  interaction = UI.ComboBox { choices = {"lingling__yitun1", "lingling__yitun2"} },
  card_filter = function (self, player, to_select, selected)
    if self.interaction.data == "lingling__yitun1" then
      return #selected < 2
    elseif self.interaction.data == "lingling__yitun2" then
      return false
    end
  end,
  target_filter = function (self, player, to_select, selected)
    if self.interaction.data == "lingling__yitun1" then
      return #selected == 0 and to_select ~= player.id
    elseif self.interaction.data == "lingling__yitun2" then
      return false
    end
  end,
  feasible = function (self,  player, selected, selected_cards)
    if self.interaction.data == "lingling__yitun1" then
      return #selected == 1 and #selected_cards > 0 and #selected_cards < 3
    elseif self.interaction.data == "lingling__yitun2" then
      return #selected == 0 and #selected_cards == 0
    end
  end,
}
Fk:addSkill(yitun_active)
hanshizhong:addSkill(jinglv)
hanshizhong:addSkill(yitun)
Fk:loadTranslationTable{
  ["lingling__hanshizhong"] = "韩世忠",
  ["#lingling__hanshizhong"] = "辅世良臣",
  ["illustrator:lingling__hanshizhong"] = "伊达未来",
  ["designer:lingling__hanshizhong"] = "伶",

  ["lingling__jinglv"] = "劲旅",
  [":lingling__jinglv"] = "当你对其他角色使用单体锦囊牌结算后，你可以对其造成1点伤害，其下回合出牌阶段可以将一张牌当该锦囊牌对你使用"..
  "（每回合每种牌名限一次）。",
  ["lingling__jinglv&"] = "劲旅",
  [":lingling__jinglv&"] = "出牌阶段，你可以将一张牌当记录的锦囊牌对韩世忠使用（每回合每种牌名限一次）。",
  ["lingling__yitun"] = "移屯",
  [":lingling__yitun"] = "当其他角色使用锦囊牌指定你为目标后，你可以选择：将至多两张牌交给一名其他角色，获得牌的角色"..
  "跳过下回合的判定阶段和弃牌阶段；判定，红色则对你无效。"..
  "<br><br> <font color = '#a40000'>忠贯日月，靡渝金石之坚。功若丘山，具焕旂常之纪。",
  ["#lingling__jinglv-invoke"] = "劲旅：是否对 %dest 造成1点伤害？其下回合出牌阶段可以将一张牌当【%arg】对你使用",
  ["#lingling__jinglv&"] = "劲旅：你可以将一张牌当记录的锦囊牌对韩世忠使用",
  ["lingling__yitun_active"] = "移屯",
  ["#lingling__yitun-invoke"] = "移屯：你可以执行一项",
  ["lingling__yitun1"] = "将至多两张牌交给一名角色，其跳过判定和弃牌阶段",
  ["lingling__yitun2"] = "进行判定，红色则此牌对你无效",
  ["@@lingling__yitun"] = "跳过判定弃牌阶段",
  ["@@lingling__yitun-turn"] = "跳过判定弃牌阶段",
}

local diqing = General(extension, "lingling__diqing", "song", 4)
local zhaqiao = fk.CreateActiveSkill{
  name = "lingling__zhaqiao",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__zhaqiao",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected)
    return #selected == 0 and (player:getNextAlive().id == to_select or player:getLastAlive().id == to_select)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    if #room.draw_pile == 0 then return end
    local all_cards, cards = {}, {}
    for i = 1, math.min(3, #room.draw_pile), 1 do
      table.insert(all_cards, room.draw_pile[i])
    end
    local card = U.askforChooseCardsAndChoice(target, all_cards, {"OK"}, self.name, "#lingling__zhaqiao-discard", {"Cancel"})
    if #card > 0 then
      table.removeOne(all_cards, card[1])
      table.insert(cards, card[1])
      room:moveCardTo(card, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, nil, true, target.id)
      if player.dead then return end
    end
    if #all_cards > 0 then
      card = U.askforChooseCardsAndChoice(player, all_cards, {"OK"}, self.name, "#lingling__zhaqiao-discard", {"Cancel"})
      if #card > 0 then
        table.insert(cards, card[1])
        room:moveCardTo(card, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, nil, true, player.id)
      end
    end
    local ids = table.filter(cards, function (id)
      return Fk:getCardById(id).color == Card.Black
    end)
    if #ids == 2 and not target.dead then
      room:setPlayerMark(target, "@@lingling__zhaqiao", 1)
    elseif #ids == 1 and not player.dead and table.contains(room.discard_pile, ids[1]) then
      room:moveCardTo(ids, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
  end,
}
local zhaqiao_delay = fk.CreateTriggerSkill{
  name = "#lingling__zhaqiao_delay",

  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return target == player and target:getMark("@@lingling__zhaqiao") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@lingling__zhaqiao", 0)
    room:setPlayerMark(player, "@@lingling__zhaqiao-turn", 1)
    player:skip(Player.Play)
  end,
}
local yexi = fk.CreateTriggerSkill{
  name = "lingling__yexi",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash" and #AimGroup:getAllTargets(data.tos) == 1
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__yexi-invoke")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = 0
    for i = 1, 3, 1 do
      local judge = {
        who = player,
        reason = self.name,
        pattern = ".|.|spade,club",
      }
      room:judge(judge)
      if judge.card.color == Card.Black then
        n = n + 1
      end
    end
    if n > 2 then
      data.additionalDamage = (data.additionalDamage or 0) + 1
    end
    if n > 1 then
      data.additionalDamage = (data.additionalDamage or 0) + 1
    end
    if n > 0 then
      data.fixedResponseTimes = data.fixedResponseTimes or {}
      data.fixedResponseTimes["jink"] = 2
    end
  end,
}
zhaqiao:addRelatedSkill(zhaqiao_delay)
diqing:addSkill(zhaqiao)
diqing:addSkill(yexi)
Fk:loadTranslationTable{
  ["lingling__diqing"] = "狄青",
  ["#lingling__diqing"] = "面涅将军",
  ["illustrator:lingling__diqing"] = "珊瑚虫",
  ["designer:lingling__diqing"] = "伶",

  ["lingling__zhaqiao"] = "诈巧",
  [":lingling__zhaqiao"] = "出牌阶段限一次，你可以与一名邻家一起观看牌堆顶的三张牌，然后其可以弃置其中一张牌，你可以弃置其中一张牌，"..
  "若以此法弃置：两张黑色牌，其跳过下一个出牌阶段；一张黑色牌，你获得之。",
  ["lingling__yexi"] = "夜袭",
  [":lingling__yexi"] = "当你使用【杀】指定唯一目标后，你可以连续判定三次，每有一次为黑色，此【杀】便依次获得以下效果：须依次使用两张【闪】抵消、"..
  "伤害+1、伤害+1。"..
  "<br><br> <font color = '#a40000'>天生狄公，辅圣推忠。情存义烈，志嫉顽凶。",
  ["#lingling__zhaqiao"] = "诈巧：与一名邻家观看牌堆顶三张牌并依次可以弃置其中一张牌，根据双方弃置黑色牌数执行效果",
  ["#lingling__zhaqiao-discard"] = "诈巧：你可以弃置其中一张牌",
  ["@@lingling__zhaqiao"] = "跳过出牌阶段",
  ["@@lingling__zhaqiao-turn"] = "跳过出牌阶段",
  ["#lingling__yexi-invoke"] = "夜袭：是否进行三次判定？若为黑色此【杀】获得额外效果",
}

local liuqi = General(extension, "lingling__liuqi", "song", 4)
local yanwu = fk.CreateTriggerSkill{
  name = "lingling__yanwu",
  anim_type = "control",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and player:usedSkillTimes(self.name, Player.HistoryRound) == 0
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__yanwu-invoke::"..target.id)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "lingling__yanwu_extra", target.id)
    room:swapSeat(player, target)
    LUtil.GainRehearsalTurn(player, self.name)
  end,

  refresh_events = {fk.AfterTurnEnd},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("lingling__yanwu_extra") ~= 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:swapSeat(player, room:getPlayerById(player:getMark("lingling__yanwu_extra")))
    room:setPlayerMark(player, "lingling__yanwu_extra", 0)
  end,
}
local rufeng = fk.CreateTriggerSkill{
  name = "lingling__rufeng",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.PreCardEffect},
  can_trigger = function(self, event, target, player, data)
    return player.id == data.to and player:hasSkill(self) and data.card.trueName == "snatch"
  end,
  on_use = Util.TrueFunc,
}
local rufeng_filter = fk.CreateFilterSkill{
  name = "#lingling__rufeng_filter",
  card_filter = function(self, card, player, isJudgeEvent)
    return player:hasSkill(rufeng) and card.type == Card.TypeTrick and
      (table.contains(player:getCardIds("h"), card.id) or isJudgeEvent)
  end,
  view_as = function(self, card)
    return Fk:cloneCard(card.name, card.suit, 13)
  end,
}
local liewei = fk.CreateTriggerSkill{
  name = "lingling__liewei",
  anim_type = "offensive",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash" and
      table.find(TargetGroup:getRealTargets(data.tos), function (id)
        return id ~= player.id and not table.contains(player:getTableMark("lingling__liewei-round"), id) and
          not player.room:getPlayerById(id).dead
      end) and #player:getCardIds("he") > 1
  end,
  on_trigger = function (self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(TargetGroup:getRealTargets(data.tos)) do
      if not player:hasSkill(self) then return end
      local p = room:getPlayerById(id)
      if id ~= player.id and not p.dead and not table.contains(player:getTableMark("lingling__liewei-round"), id) and
        #player:getCardIds("he") > 1 then
        self:doCost(event, p, player, data)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local cards = player.room:askForDiscard(player, 2, 2, true, self.name, true, nil,
      "#lingling__liewei-invoke::"..target.id, true)
    if #cards == 2 then
      self.cost_data = {tos = {target.id}, cards = cards}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addTableMark(player, "lingling__liewei-round", target.id)
    local n1 = 0
    for _, id in ipairs(self.cost_data.cards) do
      n1 = n1 + Fk:getCardById(id).number
    end
    room:throwCard(self.cost_data.cards, self.name, player, player)
    if target.dead then return end
    local n2 = 0
    local cards = room:askForDiscard(target, 2, 2, true, self.name, false, nil,
      "#lingling__liewei-discard:"..player.id.."::"..n1, true)
    if #cards > 0 then
      for _, id in ipairs(cards) do
        n2 = n2 + Fk:getCardById(id).number
      end
    end
    room:throwCard(cards, self.name, target, target)
    if n1 > n2 and not target.dead then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        damageType = fk.FireDamage,
        skillName = self.name,
      }
    end
  end,
}
rufeng:addRelatedSkill(rufeng_filter)
liuqi:addSkill(yanwu)
liuqi:addSkill(rufeng)
liuqi:addSkill(liewei)
Fk:loadTranslationTable{
  ["lingling__liuqi"] = "刘锜",
  ["#lingling__liuqi"] = "闻名止啼",
  ["illustrator:lingling__liuqi"] = "伊达未来",
  ["designer:lingling__liuqi"] = "伶",

  ["lingling__yanwu"] = "演武",
  [":lingling__yanwu"] = "每轮限一次，其他角色回合结束后，你可以与其交换位置并执行一个额外回合，该回合为"..
  "<a href='ling_extra_turn'>预演回合</a>，回合结束后将位置换回。",
  ["lingling__rufeng"] = "儒风",
  [":lingling__rufeng"] = "你的锦囊牌点数视为K。【顺手牵羊】对你无效。",
  ["lingling__liewei"] = "烈围",
  [":lingling__liewei"] = "每轮每名其他角色限一次，当你使用【杀】结算后，你可以弃置两张牌，然后令目标弃置两张牌，若你此次弃置牌点数和"..
  "大于其此次弃置牌点数和，你对其造成1点火焰伤害。"..
  "<br><br> <font color = '#a40000'>自过南朝来十五年闲无如此战，必是外国起鬼兵来，我辈莫敢当也。",
  ["#lingling__yanwu-invoke"] = "演武：是否与 %dest 交换位置并执行一个预演回合？回合结束换回位置",
  ["ling_extra_turn"] = "预演回合结束时，将所有存活角色的体力值调整为此回合开始时的数值。",
  ["#lingling__rufeng_filter"] = "儒风",
  ["#lingling__liewei-invoke"] = "烈围：你可以弃两张牌，令 %dest 弃两张牌，若点数大于其，对其造成1点火焰伤害",
  ["#lingling__liewei-discard"] = "烈围：请弃置两张牌，若点数小于%arg，%src 对你造成1点火焰伤害",
}

local baozheng = General(extension, "lingling__baozheng", "song", 4, 4, General.Male)
local shengtang = fk.CreateActiveSkill{
  name = "lingling__shengtang",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__shengtang-prompt",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected)
    if #selected == 0 and to_select ~= player.id then
    local target = Fk:currentRoom():getPlayerById(to_select)
    if target and not target:isKongcheng() then
    for _, cid in ipairs(target:getCardIds('h')) do
      if player:cardVisible(cid) then
        return false end
      end
      return true
    end
  end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local cards ={}
    if #room.draw_pile>0 then
      table.insert(cards,table.random(room.draw_pile,1)[1])
    end
    local cardIds = {}
    if #room.discard_pile>0 then
      table.insert(cards,table.random(room.discard_pile,1)[1])
    end
    local id = table.random(target.player_cards[Player.Hand])
    table.insert(cards, id)
    table.shuffle(cards)
    player:showCards(cards)
    room:delay(500)
    local id2 = room:askForCardChosen(player, target, {
      card_data = {
        { "$Hand", cards }
      }
    }, self.name, "#lingling__shengtang-card")
    if id2 ~= id then
      room:sendLog{
        type = "#lingling__shengtang_bad",
        toast = true,
      }
      room:loseHp(player,1,self.name)
      table.removeOne(cards,id)
      if #cards>0 and player:isAlive() then
      room:moveCardTo(cards, Player.Hand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      end
    else
      room:doIndicate(player.id,{target.id})
      room:sendLog{
        type = "#lingling__shengtang_good",
        toast = true,
      }
      room:setPlayerMark(target,"@@lingling__shengtang_tonot",1)
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
        damageType = fk.NormalDamage
      }
    end
  end,
}
local shengtang_trigger = fk.CreateTriggerSkill{
  name = "#lingling__shengtang_trigger",
  refresh_events = {fk.TurnEnd,fk.TargetConfirming},
  can_refresh = function (self, event, target, player, data)
    if target == player and player:getMark("@@lingling__shengtang_tonot")~=0 then
    if event == fk.TargetConfirming then
      return data.card.name == "peach"
    else
    return true 
    end
  end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.TargetConfirming then
      AimGroup:cancelTarget(data, player.id)
      return true
    else
    room:setPlayerMark(target,"@@lingling__shengtang_tonot",0)
    --room:setPlayerMark(target,"@@lingling__shengtang_not-turn",1)
    end
  end,
}
--[[local shengtang_prohibit = fk.CreateProhibitSkill{
 name = "#lingling__shengtang_prohibit",
  is_prohibited = function(self, from, to, card)
      return from:getMark("@@lingling__shengtang_not-turn") ~= 0 and card.name == 'peach'
  end,
}--]]
local zhuixiong = fk.CreateTriggerSkill{
  name = "lingling__zhuixiong",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      return #player.room.alive_players > 1
    end
  end,
  on_cost = function (self, event, target, player, data)
    return true
  end,
  on_trigger = function (self, event, target, player, data)
    local room = player.room
    local ids = table.map(room.alive_players,Util.IdMapper)
    if #ids>1 then
      local tos = table.random(ids,2)
      local to = room:askForChoosePlayers(player,tos,1,1,"#lingling__zhuixiong-choose",self.name,false,true)
      if #to>0 then
        local mark = player:getTableMark("@@lingling__zhuixiong_guess")
        table.insert(mark,{tos,to[1]})
        room:setPlayerMark(player,"@@lingling__zhuixiong_guess",mark)
      end
    end
  end,
  refresh_events = {fk.Damage,fk.AfterPhaseEnd},
  can_refresh = function (self, event, target, player, data)
    if #player:getTableMark("@@lingling__zhuixiong_guess")>0 then
      if event == fk.AfterPhaseEnd then
        return player.phase == Player.Play
      else
        if target.phase == Player.Play then
      for _, group in ipairs(player:getTableMark("@@lingling__zhuixiong_guess")) do
          if table.contains(group[1],data.from.id) then
            return true
          end
      end
    end
      return false
    end
  end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.AfterPhaseEnd then
      room:setPlayerMark(player,"@@lingling__zhuixiong_guess",0)
    else
      local mark = player:getTableMark("@@lingling__zhuixiong_guess")
        for i=#mark,1,-1 do
          if table.contains(mark[i][1],data.from.id) then
            if mark[i][2] == data.from.id then
              room:sendLog{
                type = "#lingling__zhuixiong_good",
                toast = true,
              }
              room:doIndicate(player.id,{data.from.id})
              local choices = {"#lingling__zhuixiong-draw"}
              if data.from:isAlive() and not data.from:isKongcheng() then
                local can = true
                  for _, cid in ipairs(data.from:getCardIds('h')) do
                    if player:cardVisible(cid) then
                      can = false break end
                    end
                    if can == true then
                      table.insertIfNeed(choices,"#lingling__zhuixiong-go")
                    end
                  end
                  table.insertIfNeed(choices,"Cancel")
                  if #choices>0 then
                  local choise = room:askForChoice(player,choices,self.name,"#lingling__zhuixiong-pick::"..data.from.id,false,{"#lingling__zhuixiong-draw","#lingling__zhuixiong-go","Cancel"})
                        if choise == "#lingling__zhuixiong-draw" then
                          room:drawCards(player,2,self.name)
                        elseif choise == "#lingling__zhuixiong-go" then
                          Fk.skills["lingling__shengtang"]:onUse(room, {from = player.id, tos = {data.from.id}})
                        end
                      end
            end
            table.remove(mark,i) 
          end
      end
      if #mark == 0 then
        room:setPlayerMark(player,"@@lingling__zhuixiong_guess",0)
      else
        room:setPlayerMark(player,"@@lingling__zhuixiong_guess",mark)
        end
    end
  end,
}
shengtang:addRelatedSkill(shengtang_trigger)
--shengtang:addRelatedSkill(shengtang_prohibit)
baozheng:addSkill(shengtang)
baozheng:addSkill(zhuixiong)
Fk:loadTranslationTable{
  ["lingling__baozheng"] = "包拯",
  ["#lingling__baozheng"] = "包青天",
  ["designer:lingling__baozheng"] = "伶",
  ["illustrator:lingling__baozheng"] = "珊瑚虫",

  ["lingling__shengtang"] = "升堂",
  [":lingling__shengtang"] = "出牌阶段限一次，你可以将一名手牌对你均不可见的其他角色的随机一张手牌与牌堆和弃牌堆中随机各一张牌混合，然后你猜测哪张牌来自其手牌，若：猜对，你对其造成1点伤害且其成为【桃】的目标时取消之直到其的回合结束；猜错，你失去1点体力并获得其中不为手牌的牌。",
  ["lingling__zhuixiong"] = "追凶",
  [":lingling__zhuixiong"] = "回合结束时，你从随机两名角色中猜测直到你的下个出牌阶段结束，其中哪名角色先于其出牌阶段内造成伤害，若猜对，其造成此伤害后你可以摸两张牌或对其发动“升堂”。"..
  "<br><br> <font color = '#a40000'>关节不到，有阎罗包老。",

  ["#lingling__shengtang-prompt"] = "升堂:将一名其他角色的一张手牌与牌堆顶，弃牌堆各一张牌混合后，猜测哪张来自其手牌",
  ["#lingling__shengtang-card"] = "升堂:选择你认为来自其手牌的一张牌",
  ["@@lingling__shengtang_not-turn"]="被升堂",
  ["#lingling__zhuixiong-choose"]="追凶：猜测他们中哪一位在其出牌阶段内先造成伤害",
  ["#lingling__zhuixiong-pick"]="追凶：凶手是 %dest ！你准备做些什么？",
  ["#lingling__zhuixiong-draw"]="摸两张牌",
  ["#lingling__zhuixiong-go"]="对其发动“升堂”！",
  ["@@lingling__zhuixiong_guess"]="追凶中……",
  ["@@lingling__shengtang_tonot"]="被升堂",
  ["#lingling__shengtang_good"]="今天谁也救不了你！来人！狗头铡伺候！",
  ["#lingling__shengtang_bad"]="此事颇有蹊跷！待本府再细细定夺。",
  ["#lingling__zhuixiong_good"]="天理昭昭！你哪里逃！",
}

local zhaoguangyi = General(extension, "lingling__zhaoguangyi", "song", 4)
local zeshu = fk.CreateActiveSkill{
  name = "lingling__zeshu",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  prompt = "#lingling__zeshu",
  can_use = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:drawCards(1, self.name)
    if player.dead or #room:getOtherPlayers(player) == 0 then return end
    if #table.filter(player:getCardIds("h"), function (id)
      return Fk:getCardById(id).trueName == "jink" and not player:prohibitDiscard(id)
    end) < 2 and
    table.every(room:getOtherPlayers(player), function (p)
      return p:isNude()
    end) then return end
    local success, dat = room:askForUseActiveSkill(player, "lingling__zeshu_active", "#lingling__zeshu-choice", false, nil, false)
    if success and dat then
      local target = room:getPlayerById(dat.targets[1])
      if #dat.cards > 0 then
        room:throwCard(dat.cards, self.name, player, player)
        if not target.dead then
          room:loseHp(target, 1, self.name)
        end
      else
        local cards = room:askForDiscard(target, 2, 2, true, self.name, false, nil, "#lingling__zeshu-discard")
        if not target.dead then
          if not table.find(cards, function (id)
            return Fk:getCardById(id).trueName == "jink"
          end) then
            target:drawCards(2, self.name)
          end
        end
      end
    end
  end,
}
local zeshu_active = fk.CreateActiveSkill{
  name = "lingling__zeshu_active",
  min_card_num = 0,
  target_num = 1,
  interaction = function ()
    return UI.ComboBox { choices = {"lingling__zeshu1", "lingling__zeshu2"} }
  end,
  card_filter = function (self, player, to_select, selected)
    if self.interaction.data == "lingling__zeshu1" then
      return #selected < 2 and Fk:getCardById(to_select).trueName == "jink" and not player:prohibitDiscard(to_select)
    elseif self.interaction.data == "lingling__zeshu2" then
      return false
    end
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    if to_select == player.id then return end
    if self.interaction.data == "lingling__zeshu1" then
      return true
    elseif self.interaction.data == "lingling__zeshu2" then
      return not Fk:currentRoom():getPlayerById(to_select):isNude()
    end
  end,
  feasible = function (self,  player, selected, selected_cards)
    if self.interaction.data == "lingling__zeshu1" then
      return #selected == 1 and #selected_cards == 2
    elseif self.interaction.data == "lingling__zeshu2" then
      return #selected == 1 and #selected_cards == 0
    end
  end,
}
local kaike = fk.CreateTriggerSkill{
  name = "lingling__kaike",
  anim_type = "support",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and data.card.type == Card.TypeTrick then
      local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn)
      if turn_event == nil or turn_event.data[1] ~= target then return end
      local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function(e)
        local use = e.data[1]
        return use.from == target.id and use.card.type == Card.TypeTrick
      end, Player.HistoryTurn)
      return #events == 2 and events[2] == player.room.logic:getCurrentEvent()
    end
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#lingling__kaike-invoke::"..target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, self.name)
    if not player.dead and not player:isNude() and not target.dead and target ~= player then
      local card = room:askForCard(player, 1, 1, true, self.name, false, nil, "#lingling__kaike-give::"..target.id)
      room:moveCardTo(card, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, false, player.id)
    end
  end,
}
local yiwu = fk.CreateActiveSkill{
  name = "lingling__yiwu",
  anim_type = "drawcard",
  min_card_num = 1,
  target_num = 0,
  prompt = "#lingling__yiwu",
  can_use = Util.TrueFunc,
  card_filter = function(self, player, to_select, selected)
    local card = Fk:getCardById(to_select)
    return card.sub_type == Card.SubtypeWeapon or card.trueName == "slash"
  end,
  on_use = function(self, room, effect)
    room:recastCard(effect.cards, room:getPlayerById(effect.from), self.name)
  end,
}
local yiwu_prohibit = fk.CreateProhibitSkill{
  name = "#lingling__yiwu_prohibit",
  main_skill = yiwu,
  prohibit_use = function(self, player, card)
    return player:hasSkill(yiwu) and player.phase == Player.Play and
      player:usedSkillTimes("lingling__yiwu", Player.HistoryPhase) == 0 and card.trueName == "slash"
  end,
}
Fk:addSkill(zeshu_active)
yiwu:addRelatedSkill(yiwu_prohibit)
zhaoguangyi:addSkill(zeshu)
zhaoguangyi:addSkill(kaike)
zhaoguangyi:addSkill(yiwu)
Fk:loadTranslationTable{
  ["lingling__zhaoguangyi"] = "赵光义",
  ["#lingling__zhaoguangyi"] = "掣国权主",
  ["designer:lingling__zhaoguangyi"] = "伶",
  ["illustrator:lingling__zhaoguangyi"] = "珊瑚虫",

  ["lingling__zeshu"] = "择术",
  [":lingling__zeshu"] = "出牌阶段限一次，你可以摸一张牌，然后选择：弃置两张【闪】，令一名其他角色失去1点体力；令一名其他角色弃置两张牌，"..
  "若未弃置【闪】，其摸两张牌。",
  ["lingling__kaike"] = "开科",
  [":lingling__kaike"] = "当一名角色于回合内使用第二张锦囊牌后，你可以摸一张牌并交给其一张牌。",
  ["lingling__yiwu"] = "抑武",
  [":lingling__yiwu"] = "出牌阶段，你可以重铸武器牌或【杀】，若你未如此做，本阶段你不能使用【杀】。"..
  "<br><br> <font color = '#a40000'>积弱虚外从此始，天子门生自此开。",
  ["#lingling__zeshu"] = "择术：摸一张牌，然后对一名其他角色选择一项效果",
  ["lingling__zeshu_active"] = "择术",
  ["#lingling__zeshu-choice"] = "择术：请选择一项",
  ["lingling__zeshu1"] = "弃两张【闪】，令一名角色失去体力",
  ["lingling__zeshu2"] = "令一名角色弃两张牌，未弃置【闪】其摸两张牌",
  ["#lingling__zeshu-discard"] = "择术：弃两张牌，若未弃置【闪】则摸两张牌",
  ["#lingling__kaike-invoke"] = "开科：是否摸一张牌并交给 %dest 一张牌？",
  ["#lingling__kaike-give"] = "开科：请交给 %dest 一张牌",
  ["#lingling__yiwu"] = "抑武：重铸武器牌或【杀】",
}

return extension
